package com.fs.ibox_h.web;

import com.fs.ibox_h.pojo.Collection;
import com.fs.ibox_h.pojo.IdCollection;
import com.fs.ibox_h.pojo.Type;
import com.fs.ibox_h.servie.CollectionService;
import com.fs.ibox_h.servie.IdCollectionService;
import com.fs.ibox_h.servie.TypeService;
import com.fs.ibox_h.util.*;
import com.fs.ibox_h.vo.*;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BEncoderStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.*;

@WebServlet(name = "CollectionServlet", value = "/CollectionServlet/*")
public class CollectionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();
        if ("/add".equals(path)){
            add(request,response);
        }
        else if("/queryAll".equals(path)){
            queryAll(request,response);
        }
        else if ("/queryByCondition".equals(path)){
            queryByCondition(request,response);
        }
        else if("/queryByname".equals(path)){
            queryByname(request,response);
        }
        else if("/queryAllType".equals(path)){
            queryAllType(request,response);
        }
        else if("/addtype".equals(path)){
            addtype(request,response);
        }
        else if ("/del".equals(path)){
            del(request,response);
        }
        else if("/queryAllIdCo".equals(path)){
            queryAllIdCo(request,response);
        }
        else if("/queryByIdCondition".equals(path)){
            queryByIdCondition(request,response);
        }
        else if("/queryAllCname".equals(path)){
            queryAllCname(request,response);
        }


    }

    private void queryAllCname(HttpServletRequest request, HttpServletResponse response) throws IOException {
        IdCollectionService bean = BeanFactory.createBean(IdCollectionService.class);
        List<StatsCname> statsCnames = bean.selectAllCnaem();
        ResponseData responseData = ResponseDataUtil.buildOk(statsCnames);
        ResponseJSONUtil.responseJSON(responseData,response);
    }

    private void queryByIdCondition(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int[] ints = obtainCurrentPagePageSize(request);
        IdCollectionCondition idCollectionCondition = new IdCollectionCondition();
        String staid = request.getParameter("staid");
        String endid = request.getParameter("endid");
        String name = request.getParameter("name");
        String state = request.getParameter("state");
        if(staid!=null&&!staid.isEmpty()){
            idCollectionCondition.setStaid(Integer.parseInt(staid));
        }
        if(endid!=null&&!endid.isEmpty()){
            idCollectionCondition.setEndid(Integer.parseInt(endid));
        }
        if(state!=null&&!state.isEmpty()){
            idCollectionCondition.setCstate(Integer.parseInt(state));
        }
        idCollectionCondition.setName(name);
        IdCollectionService bean = BeanFactory.createBean(IdCollectionService.class);
        Page<IdCollection> idCollectionPage = bean.selceByIdCondition(ints[0], ints[1], idCollectionCondition);
        ResponseData responseData = ResponseDataUtil.buildOk(idCollectionPage);
        ResponseJSONUtil.responseJSON(responseData,response);
    }

    private void queryAllIdCo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        IdCollectionService bean = BeanFactory.createBean(IdCollectionService.class);
        List<IdCollection> idCollections = bean.selectAll();
        ResponseData responseData = ResponseDataUtil.buildOk(idCollections);
        ResponseJSONUtil.responseJSON(responseData,response);
    }

    private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        TypeService bean = BeanFactory.createBean(TypeService.class);
        bean.dele(name);
        ResponseData msgs = ResponseDataUtil.buildOk("删除成功");
        ResponseJSONUtil.responseJSON(msgs,response);
    }

    private void addtype(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        TypeService bean = BeanFactory.createBean(TypeService.class);
//         =bean.selectBytype(name);
        bean.addType(name);
        ResponseData msgs = ResponseDataUtil.buildOk("添加成功");
        ResponseJSONUtil.responseJSON(msgs,response);

    }

    private void queryAllType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TypeService bean = BeanFactory.createBean(TypeService.class);
        List<Type> types = bean.selectAll();
        ResponseData responseData = ResponseDataUtil.buildOk(types);
        ResponseJSONUtil.responseJSON(responseData,response);
    }

    private void queryByname(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cname = request.getParameter("cname");
        IdCollectionService bean = BeanFactory.createBean(IdCollectionService.class);
        List<Position> positions = bean.selectByCname(cname);
        ResponseData responseData = ResponseDataUtil.buildOk(positions);
        ResponseJSONUtil.responseJSON(responseData,response);


    }

    private void queryByCondition(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int[] ints = obtainCurrentPagePageSize(request);
//        int currentPageInt = 1;  //默认第一页
//        String currentPage = request.getParameter("currentPage");
//        if(currentPage != null && !currentPage.isEmpty()){
//            //前端传递页码,  把String类型转换为int类型
//            currentPageInt = Integer.parseInt(currentPage);
//        }
//        int pageSizeInt = 3;  //默认页容量
//        String pageSize = request.getParameter("pageSize");
//        if(pageSize != null && !pageSize.isEmpty()){
//            //前端传递页码,  把String类型转换为int类型
//            pageSizeInt = Integer.parseInt(pageSize);
//        }
        CollectionCondition collectionCondition = new CollectionCondition();
        String cname = request.getParameter("cname");
        String cstate = request.getParameter("cstate");

        if (cstate!=null&&!cstate.isEmpty()){
            int intcstate=Integer.parseInt(cstate);
            collectionCondition.setCstate(intcstate);
        }
        collectionCondition.setCname(cname);

        CollectionService bean = BeanFactory.createBean(CollectionService.class);

//        List<Collection> collections = bean.selceByCondition(currentPageInt, pageSizeInt, collectionCondition);
        Page<Collection> collectionPage = bean.selceByCondition(ints[0], ints[1], collectionCondition);
        ResponseData responseData = ResponseDataUtil.buildOk(collectionPage);

        ResponseJSONUtil.responseJSON(responseData,response);

    }

    private void queryAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CollectionService bean = BeanFactory.createBean(CollectionService.class);
        List<Collection> collections = bean.selectAll();
        ResponseData responseData = ResponseDataUtil.buildOk(collections);
        ResponseJSONUtil.responseJSON(responseData,response);
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Collection collection = new Collection();
        //1.创建DiskFileItemFactory对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //2.创建一个解析Request对象解析器 ServletFileUpload
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()){
                    String Name = fileItem.getFieldName();
                    String value = fileItem.getString("UTF-8");
                    if ("cname".equals(Name)){
                        collection.setCname(value);
                    }
                    else if("type".equals(Name)){
                        int inttype=Integer.parseInt(value);
                        collection.setType(inttype);
                    }
                    else if("releasenum".equals(Name)){
                        int intnum=Integer.parseInt(value);
                        collection.setReleasenum(intnum);
                    }
                    else if("price".equals(Name)){
                        double dprice=Double.parseDouble(value);
                        collection.setPrice(dprice);
                    }
                    else if("content".equals(Name)){
                        collection.setContent(value);
                    }
                    else if("startdate".equals(Name)){
//                        System.out.println(value);
                        Long longv =Long.parseLong(value);
                        Date date = new Date(longv);

                        collection.setStartdate(date);
                    }
                    else if("enddate".equals(Name)){
                        Long longv=Long.parseLong(value);
                        Date date = new Date(longv);
                        collection.setEnddate(date);
                    }

                }
                else {
                    String savePath = "D:/upload/";
                    //得到上传的文件名 getName()
                    String uploadFilename = fileItem.getName();
                    String saveFile =  FileUploadUtil.randomFilename()+FileUploadUtil.getFileSuffix(uploadFilename);
                    collection.setCimg("/img/"+saveFile);
                    fileItem.write(new File(savePath,saveFile));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        CollectionService bean = BeanFactory.createBean(CollectionService.class);
        bean.addcollection(collection);
        ResponseData msg = ResponseDataUtil.buildOk("添加成功");
        ResponseJSONUtil.responseJSON(msg,response);

    }
private int[] obtainCurrentPagePageSize(HttpServletRequest request){
        int[] a=new int[2];
    int currentPageInt = 1;  //默认第一页
    String currentPage = request.getParameter("currentPage");
    if(currentPage != null && !currentPage.isEmpty()){
        //前端传递页码,  把String类型转换为int类型
        currentPageInt = Integer.parseInt(currentPage);
    }
    int pageSizeInt = 3;  //默认页容量
    String pageSize = request.getParameter("pageSize");
    if(pageSize != null && !pageSize.isEmpty()){
        //前端传递页码,  把String类型转换为int类型
        pageSizeInt = Integer.parseInt(pageSize);
    }
    a[0]=currentPageInt;
    a[1]=pageSizeInt;
    return a;
}




}
